import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import server.Context;
import server.Host;
import server.Mapper;

import javax.xml.parsers.SAXParser;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
import java.util.concurrent.*;

/**
 * @ClassName BootStrap
 * @Deseription MiniCat 的主类
 * @Author fx
 * @Date 2021/1/10 0010 15:38
 * @Version 1.0
 **/
public class BootStrap {

    /** 定义socket监听的端口*/
    private int port  = 8080;

    private Map<String,HttpServlet> servletMap = new HashMap<String, HttpServlet>();

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    /**
     * @Author fx
     * @Description MiniCat启动方法
     * @ClassName BootStrap
     * @Date 15:42 2021/1/10 0010
     * @Param 
     * @return 
     **/
    public void start() throws Exception {
        //加载server服务器
        loadServer();
        //加载servlet
        loadServlet();

        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("------->miniCat start and port :" + port);


        /*
            完成Minicat 1.0版本
            需求：浏览器请求http://localhost:8080,返回一个固定的字符串到页面"Hello Minicat!"
         */
        /*while(true){
            Socket socket = serverSocket.accept();
            // 接收socket请求，获取输出流
            OutputStream outputStream = socket.getOutputStream();
            String data = "Hello   Minicat";
            String responseTest = HttpProtocolUtil.getHead200(data.getBytes().length) + data;
            outputStream.write(responseTest.getBytes());
            socket.close();
        }*/

        /**
         * 完成Minicat 2.0版本
         * 需求：封装Request和Response对象，返回html静态资源文件
         */
        /*while (true){
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            response.outputHtml(request.getUrl());
            socket.close();
        }*/

        /**
         * 完成Minicat 3.0版本
         * 需求：可以请求动态资源（Servlet）
         */
        /*while(true){
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            if(servletMap.get(request.getUrl()) == null){
               //静态资源处理
               response.outputHtml(request.getUrl());
            }else{
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request,response);
            }
            socket.close();
        }*/

        /**
         * 使用线程池
         **/

        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new
                ThreadPoolExecutor.AbortPolicy();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );
        try {
            while(true) {
                Socket socket = serverSocket.accept();
                RequestProcessor requestProcessor = new RequestProcessor(socket,servletMap);
                //requestProcessor.start();
                threadPoolExecutor.execute(requestProcessor);
            }
        }catch (Exception e){
            e.printStackTrace();
        }


    }

    /**
     * @Author fx
     * @Description 加载servlet配置信息
     * @ClassName BootStrap
     * @Date 17:08 2021/1/10 0010
     * @Param
     * @return
     **/
//    private void loadServlet() {
//        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("web.xml");
//        SAXReader saxReader = new SAXReader();
//        try {
//            Document document = saxReader.read(inputStream);
//            Element rootElement = document.getRootElement();
//
//            List<Element> selectNodes = rootElement.selectNodes("//servlet");
//            for (Element selectNode : selectNodes) {
//                // <servlet-name>lagou</servlet-name>
//                Element sevletnamElement = (Element) selectNode.selectSingleNode("servlet-name");
//                String servletName = sevletnamElement.getStringValue();
//                // <servlet-class>lagou</servlet-class>
//                Element servletClassElement = (Element) selectNode.selectSingleNode("servlet-class");
//                String servletClass = servletClassElement.getStringValue();
//
//                // 根据servlet-name的值查找 url-pattern
//                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='"+servletName+"']");
//                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
//                servletMap.put(urlPattern,(HttpServlet)Class.forName(servletClass).newInstance());
//            }
//        } catch (DocumentException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (InstantiationException e) {
//            e.printStackTrace();
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        }
//    }
    private static String TARGET_DIR = "/target/classes/";
    private void loadServlet() {
        //从server.xml中获取应用路径，并解析web.xml文件，获取servlet
        Set<String> hostSet = mapper.getMapper().keySet();
        for (String s : hostSet) {
            Host host = mapper.getMapper().get(s);
            String appBase = host.getAppBase();
            List<Context> contextList = host.getContexts();
            for (Context context : contextList) {
                String contextPrefix = context.getPrefix();
                String contextPathpath = context.getPath();
                //加载web.xml的内容，编译后在target/classes下
                String loadPath = appBase + contextPathpath + TARGET_DIR + "/web.xml";
                File file = new File(loadPath);
                InputStream resourceAsStream = null;
                try {
                    resourceAsStream = new FileInputStream(file);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                SAXReader saxReader = new SAXReader();
                try {
                    Document document = saxReader.read(resourceAsStream);
                    Element rootElement = document.getRootElement();
                    //加载servlet
                    List<Element> selectNodes = rootElement.selectNodes("//servlet");
                    for (int i = 0; i < selectNodes.size(); i++) {
                        Element element = selectNodes.get(i);
                        // <servlet-name>lagou</servlet-name>
                        Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                        String servletName = servletnameElement.getStringValue();
                        // <servlet-class>server.xxxServlet</servlet-class>
                        Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                        String servletClass = servletclassElement.getStringValue();
                        //通过urlClassLoader加载类
                        File file1 = new File(appBase + contextPathpath + TARGET_DIR);
                        // Convert File to a URL
                        URL url = file1.toURL();
                        URL[] urls = new URL[]{url};
                        ClassLoader cl = new URLClassLoader(urls);
                        Class myClass = cl.loadClass(servletClass);
                        // 根据servlet-name的值找到url-pattern
                        Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                        // lagou
                        String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                        servletMap.put(contextPrefix + urlPattern, (HttpServlet) myClass.newInstance());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private Mapper mapper = new Mapper();
    /**
     * @Author fx
     * @Description 加载server配置文件
     * @ClassName BootStrap
     * @Date 21:04 2021/1/30 0030
     * @Param
     * @return
     **/
    public void loadServer(){
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(inputStream);
            //获取根元素
            Element rootElement = document.getRootElement();
            //查找service标签
            List<Element> serviceList = rootElement.selectNodes("// service");
            for (int i = 0; i < serviceList.size(); i++) {
                Element element = serviceList.get(i);
                //取出Connector标签
                List<Element> connectorNodes = element.selectNodes("//Connector");
                Element connectorElement = connectorNodes.get(0);
                String port = connectorElement.attributeValue("port");
                this.port = Integer.parseInt(port);

                //取出Engine标签
                List<Element> engineList = element.selectNodes("//Engine");
                Element engineElement = engineList.get(0);

                //取出Host标签
                List<Element> hostElements = engineElement.selectNodes("//Host");
                for (int k = 0; k < hostElements.size(); k++) {
                    Element element1 = hostElements.get(k);
                    // Host标签赋值
                    Host host = new Host();
                    host.setName(element1.attributeValue("name"));
                    host.setAppBase(element1.attributeValue("appBase"));

                    List<Element> contextElements = element1.selectNodes("//Context");
                    List<Context> contextList = new ArrayList<>();
                    for (Element contextElement : contextElements) {
                        Context context = new Context();
                        context.setPath(contextElement.attributeValue("path"));
                        context.setPrefix(contextElement.attributeValue("prefix"));
                        contextList.add(context);
                    }
                    host.setContexts(contextList);
                    mapper.getMapper().put(host.getName(),host);
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        BootStrap bootStrap = new BootStrap();
        try {
            bootStrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
